/*qtcoincoin Board client in C++ language
   Copyright (C) 2013  pierre80

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
#include "http_client.h"
#include "constantes.h"
#include "configboardoptions.h"
#include "parser.h"
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QUrl>
/**
 * @class http_client
 * @brief Classe du client http
 * @date 10 aout 2013
**/
http_client::http_client(QObject *parent) :QObject(parent)

{
    network_conn=new QNetworkAccessManager();
    connect(this,SIGNAL(send_add(QString)),this,SLOT(receive_add(QString)));
}
http_client::~http_client()
{
    qDebug()<<"Appel du destructeur de la classe http_client ";
    qDebug()<<"Destruction de network_conn";
    delete network_conn;
    url.detach();
    hostname.detach();
}

/**
 * @fn void create_network()
 * @brief Création du réseau
 *
 *
 */
void http_client::create_network()
{
    //connect(network_conn, SIGNAL(finished(QNetworkReply)),this, SLOT(finishedSlot(QNetworkReply)));
}
/**
 * @fn void create_request()
 * @brief Création de la requete
 *
 *
 */
void http_client::create_request(QString add)
{
    qDebug()<<"create requete\n";
    url=QUrl(add);
    requete.setUrl(url);
#if QT_VERSION >= 0x05000
    requete.setRawHeader("User-Agent",user_agent.toUtf8());
#else
    requete.setRawHeader("User-Agent",user_agent.toAscii());
#endif
    requete.setRawHeader("Accept","text/xml");
    network_conn=new QNetworkAccessManager();
    reponse=network_conn->get(QNetworkRequest(url));
    http_get_request(QNetworkRequest(url));
#if QT_VERSION >=0x05000
    hostname=url.host().toUtf8();
#else
    hostname=url.host().toAscii();
#endif
    file_www=QFileInfo(url.path());

    emit connecte();
}
/**
 * @fn void http_request()
 * @brief requete http de téléchargement
 *
 *
 */
void http_client::http_request_get(QString add, QString file, QString user_agent)
{

    error=false;
    outfile="";
    QString addandfile=add;
    addandfile.append("/");
    addandfile.append(file);
    qDebug()<<"Addresse add :";
    qDebug()<<add;
    qDebug()<<"file :"<<file;
    qDebug()<<"addandfile :"<<addandfile;
    emit send_add(addandfile);
    qDebug()<< "Hôte récupéré a partir de l'add"<<hostname;
    //On récupère les différents élements de la requete
    //QFileInfo file_info(uri.path());//Recupération du chemin du fichier
    xml_file=file_www.fileName();//Récupération du nom du fichier
    //reponse=http_get_request(addandfile);
    qDebug()<<"nom du fichier a analyser :";
    qDebug()<<xml_file;
    outfile=xml_file;
    outfile.append("_");
    outfile.append(hostname);
    connect(reponse,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(Erreur(QNetworkReply::NetworkError)));
    connect(reponse,SIGNAL(finished()),this,SLOT(export_content()));
    emit send_filename_with_url(outfile);
    emit fin_de_get();
}
/**
 * @fn void http_request_post()
 * @brief requete http de post
 *
 *
 */
void http_client::http_request_post(QString add, QString post_directory_path,QString message,QString cookie_value,QString ua)
{


    QString url_ful_post_data_send=add;
    int postlenght=message.size();
    url_ful_post_data_send.append("/");
    url_ful_post_data_send.append(post_directory_path);
    QUrl uri(url_ful_post_data_send);
    QString post_ref=uri.host();
    QString host_url=uri.host();
    //post_ref.append(uri.host());
    post_ref.prepend("http://");
    //post_ref.append("/");
    post_ref.append(post_directory_path.prepend("/"));
    qDebug()<<"post_ref="<<post_ref;
    //int message_size=message.size();
    QString add_post_host=add;
    add_post_host.mid(13);
    //QString message_post="message=";
    //network_conn=new QNetworkAccessManager;
    post_path_uri=post_directory_path;
    requete=QNetworkRequest(uri);
    requete.setRawHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
#if QT_VERSION >=0x05000
    requete.setRawHeader("User-Agent",ua.toUtf8());
    requete.setRawHeader("Cookie",cookie_value.toLatin1());
#else
    requete.setRawHeader("User-Agent",ua.toAscii());
    requete.setRawHeader("Cookie",cookie_value.toAscii());
#endif
    requete.setRawHeader("Accept","text/xml");
    requete.setRawHeader("Accept-Encoding",QByteArray());
#if QT_VERSION >=0x05000
    requete.setRawHeader("Referer",post_ref.toLatin1());
#else
    requete.setRawHeader("Referer",post_ref.toAscii());
#endif
    requete.setRawHeader("Content-Lenght",QByteArray().setNum(postlenght,10));
    requete.setRawHeader("Connection","Keep-Alive");
    requete.setRawHeader("Accept-Language",QByteArray());
#if QT_VERSION >=0x05000
    requete.setRawHeader("Host",host_url.toLatin1());
    qDebug()<<"Post du message!";
    reponse_post=network_conn->post(requete,message.toLatin1());
#else
    requete.setRawHeader("Host",host_url.toAscii());  
    qDebug()<<"Post du message!";
    reponse_post=network_conn->post(requete,message.toAscii());
#endif
    connect(reponse_post,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(Erreur(QNetworkReply::NetworkError)));

    connect(reponse_post,SIGNAL(finished()),this,SLOT(fin_de_requete_post()));
    //Penser a mettre un retour vers la fenetre principale pour savoir ou en est la requete
    message="";
}

/**
 * @fn void set_add(QString add)
 * @brief requete http
 *
 *
 */
void http_client::set_add(QString add)
{

}
void http_client::telechargement()
{

}

void http_client::Erreur(QNetworkReply::NetworkError)
{
    error=true;
    reponse = qobject_cast<QNetworkReply*>(sender());
//#if QT_DEBUG
    qDebug()<<"Erreur\n";
//#endif
    emit send_state_http_get(0);
}
/**
 * @fn void save()
 * @brief Sauvegarde de la réponse sur le HDD
 *
 *Cette fonction est a supprimmer
 */
void http_client::save(void)
{
    //qDebug()<<"Fonction save";
    //qDebug()<<"xml_file vaut";
    qDebug()<<xml_file;
    //qDebug()<<"hostname ="<<hostname;
    reponse=qobject_cast<QNetworkReply*>(sender());
    parser *Parser =new parser;
    qDebug()<<"fichier_board ="<<outfile;
    QFile fichier_xml;
    fichier_xml.setFileName(outfile);
    fichier_xml.open(QIODevice::WriteOnly|QIODevice::Text);
    fichier_xml.write(reponse->readAll());
    qDebug()<<reponse->readAll();
    reponse->deleteLater();//Important évite des fuites mémoires
    emit send_filename_with_url(outfile);
    emit send_content(Parser->affiche_data());
    emit end_download();

}
void http_client::network_get_request(QString addr, QString chemin_xml, QString ua)
{
    http_request_get(addr,chemin_xml,ua);

}
void http_client::network_post_request(QString add, QString post_directory_path, QString message, QString cookie_value, QString ua)
{
    http_request_post(add,post_directory_path,message,cookie_value,ua);
}
void http_client::receive_file_name_from_download(QString file)
{
    fichier_a_parser=file;
}
void http_client::end_download_ok()
{
    qDebug()<<"Téléchargement du fichier fini";
}
QNetworkReply *http_client::http_get_request(const QNetworkRequest &requete)
{
      return network_conn->get(requete);
}
 QNetworkReply *http_client::http_post_request(const QNetworkRequest &requete,QString &postData)
 {
#if QT_VERSION >= 0x05000
     return network_conn->post(requete,postData.toUtf8());
#else
    return network_conn->post(requete,postData.toAscii());
#endif
 }
void http_client::export_content()
{

    const QByteArray data_send(reponse->readAll());
    emit finish_export();
    emit send_content_req_to_parse(data_send);
    emit send_state_http_get(1);


}
void http_client::fin_de_requete_post()
{
    emit finish_post();
    reponse_post->deleteLater();
}
void http_client::detruire_response()
{

        reponse->close();/*Fermeture*/
        reponse->deleteLater();/*Important*/
//#if QT_DEBUG
    qDebug()<<"Destruction de la requete get";
//#endif
}
void http_client::detruire_response_post()
{
    //
    reponse_post->close();
    reponse_post->deleteLater();
    //requete.~QNetworkRequest ();
//#if QT_DEBUG
    qDebug()<<"Destruction de la requete post";
//#endif

}
void http_client::receive_add(QString add)
{
    create_request(add);
}
